package com.handler.http.message.util.sign;

import com.alibaba.fastjson.JSON;
import com.handler.http.message.util.StringUtils;
import org.springframework.util.Assert;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author chenkui
 */
public class SignatureUtils {
    /**
     * 仅供bean对象使用,基础的数据结构不可使用，如list,map,iterator,string
     *
     * @return
     */
    public static String getSignContent(Object object) {
        StringBuilder content = new StringBuilder();
        Map<String, String> map = convertSortMap(object);
        if (map != null) {
            List<String> keys = new ArrayList<String>(map.keySet());
            Collections.sort(keys);
            int index = 0;
            for (String key : keys) {
                String value = map.get(key);
                if (StringUtils.areNotEmpty(key, value)) {
                    content.append(index == 0 ? "" : "&").append(key).append("=").append(value);
                    index++;
                }
            }
        }
        return content.toString();
    }

    /**
     * 仅供bean对象使用,基础的数据结构不可使用，如list,map,iterator,string
     *
     * @param bean
     * @return
     */
    public static Map<String, String> convertSortMap(Object bean) {
        Map<String, String> treeMap = null;
        try {
            treeMap = new TreeMap<String, String>();
            Field[] declaredFields = bean.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                Object value = field.get(bean);
                String name = field.getName();
                if (value != null && org.apache.commons.lang3.StringUtils.isNotBlank(name)) {
                    treeMap.put(field.getName(), JSON.toJSONString(value));
                }
            }
        } catch (Exception e) {
            Assert.state(false, "转换对象为map异常:" + e.getMessage());
        }
        return treeMap;
    }

    public static String getSignContentFormMap(Map<String, String> map) {
        StringBuilder content = new StringBuilder();
        if (map != null) {
            List<String> keys = new ArrayList<String>(map.keySet());
            Collections.sort(keys);
            int index = 0;
            for (String key : keys) {
                String value = map.get(key);
                if (StringUtils.areNotEmpty(key, value)) {
                    content.append(index == 0 ? "" : "&").append(key).append("=").append(value);
                    index++;
                }
            }
        }
        return content.toString();
    }

    /**
     * 签名
     *
     * @param content
     * @param secretKey 秘钥
     * @return
     */
    public static String sign(String content, String secretKey) {
        String signMD5 = MD5.sign(content + secretKey, "utf-8");
        return Base64.encode(signMD5.getBytes());
    }

    /**
     * 验签
     *
     * @param verifySign
     * @param params
     * @param secretKey
     * @return
     */
    public static boolean verify(String verifySign, Map<String, String> params, String secretKey) {
        try {
            String baseDecode = new String(Base64.decode(verifySign), "utf-8");
            return MD5.verify(getSignContentFormMap(params) + secretKey, baseDecode, "utf-8");
        } catch (Exception e) {
            Assert.state(false, "校验签名异常:" + e.getMessage());
        }
        return false;
    }

    /**
     * 对象转json
     *
     * @param object
     * @return
     */
    public static String modeconvertToString(Object object) {
        return new JSONWriter().write(object, true);
    }
}
